import wsgiref.handlers
from django.utils import simplejson
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp \
     import template
from google.appengine.ext import db

class Treat(db.Model):
        author = db.UserProperty()
        title = db.StringProperty()
        page = db.TextProperty()
        date = db.DateTimeProperty(auto_now_add=True)
        def to_dict(self):
               return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

class Ajax(webapp.RequestHandler):
        def get(self, *args):
                method = args[0]
                if method == "titles":
                        treats = Treat.all()
                        treats.filter('author =', users.get_current_user())
                        treats.order('date')
                        json = "["
                        for treat in treats:
                                json += "{\"title\":\"" + treat.title + "\", \"key\":\"" + treat.key().__str__() + "\"},"
                        if len(json) > 1:
                                json = json[:-1]
                                json += "]"
                        else:
                                json = ""
			self.response.out.write(json)
##                      self.response.out.write(simplejson.dumps([x.to_dict() for x in treats]))

        def post(self, *args):
                method = args[0]
                if method == "save":
                       t = Treat()
                       t.page = self.request.get("page")
                       t.title = self.request.get("title")
                       t.author = users.get_current_user()
                       t.put()
                       self.response.out.write(t.key().__str__())
                if method == "update":
                        t = db.get(self.request.get("treat_key"))
                        t.page = self.request.get("page")
                        t.title = self.request.get("title")
                        t.put()
                        self.response.out.write("OK")
                
class MainPage(webapp.RequestHandler):
	def get(self):
                user = users.get_current_user()
                if user:
                        nick = users.get_current_user()
                        url = users.create_logout_url(self.request.uri)
                        template_values = {
                            'nickname': nick,    
                            'logout': url,
                        }    
                        self.response.out.write(template.render('templates/main.html', template_values))
		else:
                        self.redirect(users.create_login_url(self.request.uri))
##        def post(self):
##                treat = Treat()
##                if users.get_current_user():
##                        
##                        treat.author = users.get_current_user()
##                        treat.page = self.request.get('page')
##                        treat.title = self.request.get('title')
##                        treat.put()
##                        self.redirect('/')
##                        self.response.out.write(
##                        template.render('main.html', {})
##                        )

app = webapp.WSGIApplication([
  ('/', MainPage),
  ('/ajax/(.*)', Ajax)
], debug=True)
		
def main():
 wsgiref.handlers.CGIHandler().run(app)
  
if __name__ == '__main__':
        main()
	
	
	
	
